package com.study.parse;

import io.milvus.grpc.FieldData;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ParseParam implements ApplicationContextAware, InitializingBean {

    private final List<ParseAdapter> adapters = new ArrayList<>();

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, ParseAdapter> map = applicationContext.getBeansOfType(ParseAdapter.class);
        map.forEach((k, v) -> adapters.add(v));
    }

    public <T> void resolveParamBind(T ins, Field field, FieldData fieldData, int index) {
        try {
            for (ParseAdapter adapter : adapters) {
                if (adapter.isSupport(field)) {
                    adapter.resolveParamBind(ins, field, fieldData, index);
                }
            }
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("不支持的类型" + field);
        }
    }
}
